<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use App\Constants\RespCode;
use App\Exception\BadException;
use Hyperf\Codec\Json;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;


/**
 * 逻辑正常提示
 * Class BadExceptionHandler
 * @package App\Exception\Handler
 */
class BadExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 阻止异常冒泡
        $this->stopPropagation();

        $format = [
            'success' => false,
            'message' => $throwable->getMessage(),
            'code' => $throwable->getCode() ?: RespCode::ERROR,
        ];

        return $response
            ->withAddedHeader('content-type', 'application/json; charset=utf-8')
            ->withStatus(200)
            ->withBody(new SwooleStream(Json::encode($format)));

    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof BadException;
    }
}
